package project.euler.honk.problem.to50;

import java.math.BigInteger;

final class Problem37 {

	private static boolean isRightTruncable(int value) {
		while (value > 0) {
			value = value / 10;
			if (!isPrime(value))
				return false;
		}
		return true;
	}

	private static boolean isLeftTruncable(int value) {
		int x = 10;
		while (x < value)
			x *= 10;
		while (x > 0) {
			int test = value % x;
			if (!isPrime(test))
				return false;
			x /= 10;
		}
		return true;
	}

	private static boolean isPrime(int value) {
		if (value == 1)
			return false;
		int max = (int) (Math.sqrt(value));
		for (int i = 2; i <= max; i++) {
			if (value % i == 0)
				return false;
		}
		return true;
	}

	public static void main(String[] args) {
		long start = System.currentTimeMillis();
		int sum = 0;
		BigInteger current = BigInteger.valueOf(22);
		int c = 0;
		while (c < 11) {
			current = current.nextProbablePrime();
			int val = current.intValue();
			if (isRightTruncable(val)) {
				if (isLeftTruncable(val)) {
					c++;
					sum += val;
				}
			}
		}
		long end = System.currentTimeMillis();
		System.out.println("Result: " + sum + " Time: " + (end - start));
	}

}
